package com.mijia.rtkdemo;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.mijia.rtk.LocationListener;
import com.mijia.rtk.SatelliteInfo;
import com.mijia.rtk.handevice;
import com.mijia.rtk.ConfigDeviceInfoListener;
import com.mijia.rtk.ntripService;
import com.mijia.rtkdemo.base.App;
import com.mijia.rtkdemo.base.AppConst;
import com.mijia.rtkdemo.bluetooth.DeviceListDialogFragment;
import com.mijia.rtkdemo.databinding.ActivityMainBinding;
import com.mijia.rtkdemo.event.*;


import android.widget.Toast;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.wandersnail.commons.helper.PermissionsRequester2;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    ActivityMainBinding mViewBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(mViewBinding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        if (!App.BUS.isRegistered(this)) {
            App.BUS.register(this);
            Log.d(TAG, "-----App.BUS.register");
        }


        initViews();
        initDatas();
        initialize();

        mViewBinding.btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mViewBinding.btnConnect.getText().equals("connect")){
                    showDialog();
                }else handevice.disconnect();

            }
        });

        mViewBinding.btnPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_LONG).show();
                if(mViewBinding.btnPause.getText().equals("pause")){
                    mViewBinding.btnPause.setText("continue");
                }else mViewBinding.btnPause.setText("pause");

            }
        });

        mViewBinding.btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_LONG).show();
                mViewBinding.tvBtrevmsg.setText("");
            }
        });

        mViewBinding.btnGetcors.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handevice.getAccount();
                //Toast.makeText(MainActivity.this,"btnGetcors",Toast.LENGTH_LONG).show();

            }
        });

        mViewBinding.btnSetcors.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String  ip=mViewBinding.etip.getText().toString();
                String  port=mViewBinding.etport.getText().toString();
                String  user=mViewBinding.etuser.getText().toString();
                String  password=mViewBinding.etpassword.getText().toString();
                String  sourcelist=mViewBinding.etsourcelist.getText().toString();

                handevice.setAccount(ip,port,user,password,sourcelist);
                //Toast.makeText(MainActivity.this,"btnGetcors",Toast.LENGTH_LONG).show();
            }
        });

        mViewBinding.btnSetPhoneCors.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                String  ip=mViewBinding.etip.getText().toString();
                String  port=mViewBinding.etport.getText().toString();
                String  user=mViewBinding.etuser.getText().toString();
                String  password=mViewBinding.etpassword.getText().toString();
                String  sourcelist=mViewBinding.etsourcelist.getText().toString();
                //handevice.setAccount(ip,port,user,password,sourcelist);
                handevice.setPhoneAccount(ip,port,user,password,sourcelist);
            }
        }
        );



        handevice.setLocationListener(new LocationListener() {
            @Override
            public void onLocationChanged() {

            }

            @Override
            public void onRead(@NonNull String msg) {
                App.BUS.post(new DateInputMessageEventArgs(msg));
            }


            @Override
            public  void onReceiveSatellite(List<SatelliteInfo> list) {
                String  satType;
                String  signalid;
                /*
                SatelliteInfo
                satType     卫星类型  1:GP   2:GL  3:GA  4:BD   6:GI
                prn         卫星编号
                elev        高度角，度
                azi         方位角，度
                L1          L1频点信噪比 00-99dB, 值-1为空
                L2          L2频点信噪比 00-99dB, 值-1为空
                L5          L5频点信噪比 00-99dB, 值-1为空

                -以下保留，不在使用-
                snr         信噪比，00-99dB，不跟踪时为空
                signalid    卫星频点
                */
                Log.d(TAG, "list size:"+list.size());

                for (int i=0;i<list.size();i++){

                    if(list.get(i).satType==1) {
                        satType = "GPS";
                    }else if(list.get(i).satType==2){
                        satType="GLONASS";
                    }else if(list.get(i).satType==3){
                        satType="Galileo";
                    }else if(list.get(i).satType==4){
                        satType="BDS";
                    }else if(list.get(i).satType==6){
                        satType="QZSS";
                    }else{
                        satType="OTHER";
                    }

                    Log.d(TAG,  satType+
                            "，编号:"+list.get(i).prn+
                            "，高度角:"+list.get(i).elev+"°"+
                            "，方位角:"+list.get(i).azi+"°"+
                            "，L1:"+list.get(i).L1+"dB"+"，L2:"+list.get(i).L2+"dB"+"，L5:"+list.get(i).L5+"dB"
                    );

                }
            }
            @Override
            public  void onBluetoothConnStatusChange(int state) {
                /*
                0:we're doing nothing
                1:now initiating an outgoing connection
                2:now connected to a remote handevice
                */
                App.BUS.post(new SendUiStatusEventArgs(AppConst.MESSAGE_UI_UPDATE_BLUETOOTH));
            }
        });

        handevice.setConfigListener(new ConfigDeviceInfoListener() {
            @Override
            public void onGetCorsParaSuccess(@NonNull String ip, @NonNull String port, @NonNull String user, @NonNull String password, @NonNull String source) {
                Log.d(TAG, "ip:"+ip+",port:"+port+",user:"+user+",password:"+password+",source:"+source);
                App.BUS.post(new SendUiStatusEventArgs(AppConst.MESSAGE_UI_UPDATE_CORS_GET));
            }

            @Override
            public void onSetCorsParaAck(int state){
                /*state:
                1   CORS设置成功        0   CORS设置失败
                * */
                if(1==state)
                    App.BUS.post(new SendUiStatusEventArgs(AppConst.MESSAGE_UI_UPDATE_CORS_SET_SUCC));
                else
                    App.BUS.post(new SendUiStatusEventArgs(AppConst.MESSAGE_UI_UPDATE_CORS_SET_FAIL));
            }

            @Override   //手机网络cors的设置回调函数
            public void onSetPhoneCorsParaAck(int state){
                /*
                state:
                0   手机网络连接CORS成功
                1   手机网络失败：用户名、密码、挂载点 错误，验证未通过
                2   手机网络失败：IP、PORT 错误，socket连接不到对方
                3   手机网络失败：其他异常，比如手机无sim卡等
                * */
                Log.d("onSetPhoneCorsParaAck", "onSetPhoneCorsParaAck:"+state);
            }

        });



    }

    private void initialize() {
        //动态申请权限
        PermissionsRequester2 permissionsRequester = new PermissionsRequester2(this);
        permissionsRequester.setCallback(list -> {

        });
        permissionsRequester.checkAndRequest(getNeedPermissions());
    }

    private void initViews() {

    }

    private void initDatas() {

    }


    //需要进行检测的权限
    private List<String> getNeedPermissions() {
        List<String> list = new ArrayList<>();
        if (getApplicationInfo().targetSdkVersion >= 29) {//target sdk版本在29以上的需要精确定位权限才能搜索到蓝牙设备
            list.add(Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        //Android 12需要
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            list.add(Manifest.permission.BLUETOOTH_SCAN);
            list.add(Manifest.permission.BLUETOOTH_CONNECT);
        }
        return list;
    }

    private void showDialog() {
        DeviceListDialogFragment dialog = new DeviceListDialogFragment();
        dialog.setCallback(new DeviceListDialogFragment.Callback() {
            @Override
            public void onSelectedItem(String address) {
                // 连接远程蓝牙
                handevice.connect(address);
                Toast.makeText(MainActivity.this,"Select :"+address,Toast.LENGTH_LONG).show();
            }
        });
        dialog.show(MainActivity.this.getFragmentManager(), "deviceListDialogFragment");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (App.BUS.isRegistered(this)) {
            App.BUS.unregister(this);
            Log.d(TAG, "-----App.BUS.unregister");
        }
        Log.d(TAG, "onDestroy");   //test
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPosUpdat(DateInputMessageEventArgs event) {
        int textViewHeight = mViewBinding.tvBtrevmsg.getHeight();


        if(mViewBinding.tvBtrevmsg.getText().length()>10000) mViewBinding.tvBtrevmsg.setText("");

        if(mViewBinding.btnPause.getText().equals("pause")){
            mViewBinding.tvBtrevmsg.append(event.message);
            mViewBinding.scrollView.fullScroll(View.FOCUS_DOWN);
        }

        mViewBinding.tvLatitude.setText(String.format("%.9f", handevice.Latitude));
        mViewBinding.tvLongitude.setText(String.format("%.9f", handevice.Longitude));

        mViewBinding.tvAltitude.setText(String.valueOf(handevice.Altitude));
        mViewBinding.tvAltitudeCorr.setText(String.valueOf(handevice.AltitudeCorr));

        mViewBinding.tvFixType.setText(String.valueOf(handevice.FixType));
        mViewBinding.tvHdop.setText(String.valueOf(handevice.Hdop));


        mViewBinding.tvhRMS.setText(String.format("%.2f", handevice.hRMS));
        mViewBinding.tvvRMS.setText(String.format("%.2f", handevice.vRMS));

        mViewBinding.tvnSatsInView.setText(String.valueOf(handevice.nSatsInView));
        mViewBinding.tvnSatsInUse.setText(String.valueOf(handevice.nSatsInUse));

        mViewBinding.tvSpeed.setText(String.valueOf(handevice.Speed));
        mViewBinding.tvDirection.setText(String.valueOf(handevice.Direction));

        mViewBinding.tvBattVol.setText(String.valueOf(handevice.BattVol));
        mViewBinding.tvBattPower.setText(String.valueOf(handevice.BattPower)+"%");

        mViewBinding.tvCorsSta.setText(String.valueOf(handevice.CorsSta));

        /*CorsRevDatSize：设备网络接收到cors数据的字节数
        **CorsPhoneRevDatSize：手机网络接收到cors数据的字节数
        * */
        mViewBinding.tvCorsRevDatSize.setText(String.valueOf(handevice.CorsRevDatSize)+"B");

        mViewBinding.tvCorsAge.setText(String.valueOf(handevice.CorsAge));
        mViewBinding.tvUniqueSN.setText(handevice.UniqueSN);

        mViewBinding.tvHardVer.setText(handevice.HardVer);
        mViewBinding.tvSoftVer.setText(handevice.SoftVer);

        mViewBinding.tvImei.setText(handevice.Imei);
        mViewBinding.tvImsi.setText(handevice.Imsi);

        mViewBinding.tvIccid.setText(handevice.Iccid);
        mViewBinding.tvTime.setText(String.valueOf(handevice.time));

        //没有显示的接口&变量
        Log.d(TAG, "XZAng："+handevice.XZAng);   //倾斜角度
        Log.d(TAG,"Pdop:"+handevice.Pdop+",Hdop:"+handevice.Hdop+",Vdop:"+handevice.Vdop+",Tdop:"+handevice.Tdop);
        Log.d(TAG, "DSK："+handevice.Dsk);

        //查询支持的卫星系统
        Log.d(TAG, "isSupportGps："+handevice.isSupportGps+",isSupportGps()："+handevice.isSupportGps());
        Log.d(TAG, "isSupportBds："+handevice.isSupportBds+",isSupportBds()："+handevice.isSupportBds());
        Log.d(TAG, "isSupportGal："+handevice.isSupportGal+",isSupportGal()："+handevice.isSupportGal());
        Log.d(TAG, "isSupportGlo："+handevice.isSupportGlo+",isSupportGlo()："+handevice.isSupportGlo());
        Log.d(TAG, "isSupportQzss："+handevice.isSupportQzss+",isSupportQzss()："+handevice.isSupportQzss());


        //handevice.setPosFreq(1);//1,2,5,10
        Log.d(TAG, "PosFreq："+handevice.PosFreq+",getPosFreq()："+handevice.getPosFreq());


        /*配置卫星系统
        * 输入参数：true 打开  false 关闭
        * 配置一次后，重启设备，会恢复全星系统
        * */
        //handevice.setSupportGps(true);  //打开GPS
        //handevice.setSupportBds(true);  //打开BDS
        //handevice.setSupportGal(true);  //打开GAL
        //handevice.setSupportGlo(true);  //打开GLO
        //handevice.setSupportQzss(true);  //打开QZSS
        //handevice.setSupportAllGnss(true);  //打开所有的
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SendUiStatusEventArgs event) {
        int state = event.message;

        if(AppConst.MESSAGE_UI_UPDATE_BLUETOOTH==state){
            if(2==handevice.getConnectState()){
                mViewBinding.btnConnect.setText("connected");
            }else{
                mViewBinding.btnConnect.setText("connect");
            }
        }

        if(AppConst.MESSAGE_UI_UPDATE_CORS_GET==state){
            mViewBinding.etip.setText(handevice.CorsIP);
            mViewBinding.etport.setText(handevice.CorsPort);
            mViewBinding.etuser.setText(handevice.CorsUser);
            mViewBinding.etpassword.setText(handevice.CorsPassword);
            mViewBinding.etsourcelist.setText(handevice.CorsSource);
            Toast.makeText(MainActivity.this,"Get success(Cors)",Toast.LENGTH_LONG).show();
        }

        if(AppConst.MESSAGE_UI_UPDATE_CORS_SET_SUCC==state){
            Toast.makeText(MainActivity.this,"Set success(Cors)",Toast.LENGTH_LONG).show();
        }
        if(AppConst.MESSAGE_UI_UPDATE_CORS_SET_FAIL==state){
            Toast.makeText(MainActivity.this,"Set fail(Cors)",Toast.LENGTH_LONG).show();
        }

    }





}